package com.maas.util.mybatis.jpa.littlenb.conditions.provider;

import com.littlenb.mybatisjpa.util.PersistentUtil;
import com.maas.util.mybatis.jpa.littlenb.conditions.common.CT;
import com.maas.util.mybatis.jpa.littlenb.support.template.select.SelectSqlTemplate;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.SQL;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;

/**
 *
 * @param <T>
 */
public class BaseProvider<T>  {

    /**
     * 通用查询构建
     */
    private SQL selectGeneralSql(Map<String, Object> map, SQL sql, String column) {
        final T entity = (T) map.get(CT.ALIAS_ENTITY);
        final String conditionSql = (String) map.get(CT.SQL_CONDITION);
        final Map<String, Object> conditionMap = (Map<String, Object>) map.get(CT.ALIAS_CONDITION);
        final Set<String> columns = map.containsKey(CT.COLUMNS) ? (Set<String>) map.get(CT.COLUMNS) : null;
        sql.SELECT(CollectionUtils.isEmpty(columns) ? column : String.join(CT.SPILT, columns)).FROM(tableName(entity));
        if (StringUtils.isNotBlank(conditionSql)) {
            sql.WHERE(conditionSql);
        }
        if (conditionMap.containsKey(CT.ORDER_BY)) {
            sql.ORDER_BY(conditionMap.get(CT.ORDER_BY).toString());
        }
        return sql;
    }
    public String list(Map<String, Object> map) {
        final T entity = (T) map.get(CT.ALIAS_ENTITY);
        return selectGeneralSql(map, new SQL(), columns(entity)).toString();
    }

    private String columns(T entity) {
        String columns ="";
        for (Field field : PersistentUtil.getPersistentFields(entity.getClass())) {
            if (SelectSqlTemplate.selectable(field)) {
//            SET(PersistentUtil.getColumnName(field) + " = " + ColumnMetaResolver
//                .resolveSqlPlaceholder(field));
                columns += "p." + PersistentUtil.getColumnName(field)+",";
            }
        }

        return columns;
    }
    private String tableName(T entity) {

        return PersistentUtil.getTableName(entity.getClass());
    }
}
